import 'package:flutter/material.dart';
import 'package:flutter_framework/main.dart';

class TestInerited extends StatefulWidget {
  const TestInerited({super.key});

  @override
  _TestIneritedState createState() => _TestIneritedState();
}

class _TestIneritedState extends State<TestInerited> {
  @override
  Widget build(BuildContext context) {
    print('构建页面 TestInerited ');
    return Scaffold(
      appBar: AppBar(
        title: Text('模板'),
      ),
      body: InerColorWidget(
        child: Center(
          child: Column(
            children: const [
              Text('color:'),
              FooColor(),
            ],
          ),
        ),
      ),
    );
  }
}

class FooColor extends StatefulWidget {
  const FooColor({super.key});

  @override
  _FooColorState createState() => _FooColorState();
}

class _FooColorState extends State<FooColor> {
  @override
  Widget build(BuildContext context) {
    print('构建 FooColor =====');
    return Container(width: 100, height: 100, color: MyColor.of(context));
  }
}

class InerColorWidget extends StatefulWidget {
  const InerColorWidget({super.key, required this.child});

  final Widget child;

  @override
  _InerColorWidgetState createState() => _InerColorWidgetState();
}

class _InerColorWidgetState extends State<InerColorWidget> {
  Color _color = Colors.red;

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        MyColor(color: _color, child: widget.child),
        ElevatedButton(
            onPressed: () {
              setState(() {
                _color = Colors.blue;
              });
            },
            child: Text('更改颜色'))
      ],
    );
  }
}

// inheritedWidget
class MyColor extends InheritedWidget {
  const MyColor({super.key, required super.child, required this.color});

  final Color color;

  static Color of(BuildContext context, {bool rebuild = true}) {
    if (rebuild) {
      return context.dependOnInheritedWidgetOfExactType<MyColor>()!.color;
    }
    return context.findAncestorWidgetOfExactType<MyColor>()!.color;
  }

  static Color? mabyOf(BuildContext context, {bool rebuild = true}) {
    if (rebuild) {
      return context.dependOnInheritedWidgetOfExactType<MyColor>()?.color;
    }
    return context.findAncestorWidgetOfExactType<MyColor>()?.color;
  }

  @override
  bool updateShouldNotify(covariant MyColor oldWidget) {
    // 颜色改变的时候 需要rebuild
    return oldWidget.color != color;
  }
}
